/*
 * DBObjectRepresentation.java
 *
 * Created on August 1, 2007, 1:22 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.atomojo.auth.service.app;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Iterator;
import org.atomojo.auth.service.db.XMLObject;
import org.infoset.xml.InfosetFactory;
import org.infoset.xml.ItemConstructor;
import org.infoset.xml.Name;
import org.infoset.xml.XMLException;
import org.infoset.xml.util.WriterItemDestination;
import org.milowski.db.DBObject;
import org.restlet.data.MediaType;
import org.restlet.representation.OutputRepresentation;

/**
 *
 * @author alex
 */
public class DBIteratorRepresentation extends OutputRepresentation
{
   
   Name root;
   Iterator<? extends DBObject> iter;
   boolean contents;
   /** Creates a new instance of DBObjectRepresentation */
   public DBIteratorRepresentation(MediaType type,Name root,Iterator<? extends DBObject> iter)
   {
      this(type,root,iter,true);
   }
   
   /** Creates a new instance of DBObjectRepresentation */
   public DBIteratorRepresentation(MediaType type,Name root,Iterator<? extends DBObject> iter,boolean contents)
   {
      super(type);
      this.root = root;
      this.iter = iter;
      this.contents = contents;
   }
   
   public void write(OutputStream os)
      throws IOException
   {
      OutputStreamWriter w = new OutputStreamWriter(os,getCharacterSet().toString());
      try {
         WriterItemDestination dest = new WriterItemDestination(w,getCharacterSet().toString());
         ItemConstructor constructor = InfosetFactory.getDefaultInfoset().createItemConstructor();
         dest.send(constructor.createDocument());
         dest.send(constructor.createElement(root));
         while (iter.hasNext()) {
            DBObject obj = iter.next();
            if (obj instanceof XMLObject) {
               ((XMLObject)obj).generate(constructor,dest,contents);
            }
         }
         dest.send(constructor.createElementEnd(root));
         dest.send(constructor.createDocumentEnd());
      } catch (XMLException ex) {
         throw new IOException(ex.getMessage());
      }
      w.flush();
   }
   
}
